const user = {
    namespaced: true,
    state: {
        is_login: false,
        u_id : '',
        userInfo: null,
        bindPhone: false,
    },
    mutations: {
        userInfo(state, data) {
            uni.setStorageSync('userInfo', data);
            state.userInfo = data;
        },
        userId(state, uid){
            uni.setStorageSync('u_id', uid);
            state.u_id = uid;
        },
    }
    ,
    getters: {
        userInfo: function (state) {
            return state.userInfo;
        },
    },
    actions: {
        getUserProfile: function ({dispatch, commit}) {
            return new Promise((resolve, reject) => {
                uni.getUserProfile({
                    lang: "zh_CN",
                    desc: '授权',
                    success: function (res) {
                        uni.login({
                            provider: 'weixin',
                            success: function (loginRes) {
                                uni.request({
                                    url: 'https://sy-k.cn/api.php/login/wx_login', //仅为示例，并非真实接口地址。
                                    data: {
                                        code: loginRes.code,
                                        avatarUrl: res.userInfo.avatarUrl,
                                        gender: parseInt(res.userInfo.gender) === 0 || 1,
                                        nickname: res.userInfo.nickName
                                    },
                                    success: (resp) => {
                                        commit('userId',resp.data.u_id);
                                        uni.$u.http.post('/api.php/Landlord/user_info', {
                                            u_id:resp.data.u_id
                                        }).then(response => {
                                            commit('userInfo', response);
                                            resolve();
                                        }).catch(error => {
                                            console.error(error);
                                            reject();
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            })
        },
    }
};

export default user;